<?php

namespace App\Http\Requests\Admin\User\Role;

use App\Models\Permission;
use App\Models\Role;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'name'=>[
                'required',
                function($attribute,$value,$fail){
                    $where = [];
                    $where['name'] = $value;
                    $count = Role::where($where)->count('id');
                    if($count){
                        $fail(":attribute已存在");
                    }
                    if(!preg_match('/[a-zA-Z0-9_]{1,10}$/', $value)){
                        $fail(":attribute只能是字母数字_且不能多于10个字符");
                    }
                },
                'bail'
            ],
            'display_name'=>[
                'required',
                'bail'
            ],
            'description'=>[
                function($attribute,$value,$fail){
                    if(!preg_match(' /^[a-zA-Z][\w]{1,10}$|^([\x{4e0}-\x{9fa5}]|[\x{4e00}-\x{9fa5}a-z-A-Z\d_]){0,100}$/u', $value)){
                        $fail(":attribute长度不能大于100字");
                    }
                },
                'bail'
            ],
            'permissions'=>[
                Rule::requiredIf($this->request->get('set_permission',false)),
                'array',
                'nullable',
                function($attribute,$value,$fail){
                    $count = Permission::whereIn('id',$value)->count('id');
                    if($count!=count($value)){
                        $fail(":attribute错误");
                    }
                },
                'bail'
            ]
        ];
    }
    public function attributes()
    {
        return [
            'name'=>'角色标识',
            'display_name'=>'名称',
            'description'=>'描述',
            'permissions'=>'权限'
        ];
    }
}
